# app.py
import os
from flask import Flask
from dotenv import load_dotenv
from extensions import db, migrate  # ← 从这里拿 db / migrate
from flask_cors import CORS
from flask_restful import Api

from flask_jwt_extended import JWTManager


load_dotenv()


app = Flask(__name__)

# 解决跨域请求
app.config["JSON_AS_ASCII"] = False
app.config["RESTFUL_JSON"] = {'ensure_ascii': False}
CORS(app, supports_credentials=True)

#绑定数据库
app.config["SQLALCHEMY_DATABASE_URI"] = (
    f"mysql+pymysql://{os.getenv('DB_USER')}:{os.getenv('DB_PASS')}"
    f"@{os.getenv('DB_HOST','127.0.0.1')}:{os.getenv('DB_PORT','3306')}/{os.getenv('DB_NAME')}?charset=utf8mb4"
)
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False


#
app.config["JWT_SECRET_KEY"] = "5e2a6b3f9c7f3a0f82e6f44c1e37e7f4a4d7c0e1c9a0b3d8f4c3e1a9f0d2b4c6"  # ⚠️ 换成你自己的密钥

# 先初始化扩展
db.init_app(app)
migrate.init_app(app, db)

# flask db init：只需要执行一次
# flask db migrate：将orm模型生成迁移脚本
# flask db upgrade：将迁移脚本映射到数据库中

from data_models import Account,Notice,Profile,Comment# 


#-------------------添加API部分----------


api = Api(app)

jwt = JWTManager(app)

from api import (
    MemberManage,
    LoginAPI,
    NoticeAPI,
    NoticeDetailAPI,
    ProfileAPI,
    AvatarUploadAPI,
    ProfileSearch,
    ProfileList,
    ProfileStats,
    CommentAPI,
    NoticeCommentsAPI,
    StudentNoticesAPI,
    StudentCommentsAPI,
    ChangePasswordAPI,
    NoticeImageUploadAPI
)
# 注册路由
api.add_resource(MemberManage, "/members") 
api.add_resource(LoginAPI, "/login")
api.add_resource(NoticeAPI, "/notices")  
api.add_resource(NoticeDetailAPI, "/notices/<int:notice_id>")     
api.add_resource(ProfileAPI, "/profile/<string:student_id>")
api.add_resource(AvatarUploadAPI, "/profile/<string:student_id>/avatar")
api.add_resource(ProfileSearch, "/profile/search")
api.add_resource(ProfileList, "/profile/list")
api.add_resource(ProfileStats, "/profile/stats")
# api.add_resource(CommentAPI, "/notices/<int:notice_id>/comments")
# api.add_resource(NoticeCommentsAPI, "/notices/<int:notice_id>/allcomments")
api.add_resource(StudentNoticesAPI,
                 "/student/<string:student_id>/notices",  # GET 用这个
                 "/delete/notice/<int:notice_id>")  # DELETE 用这个
# api.add_resource(StudentCommentsAPI, "/students/<string:student_id>/comments")
api.add_resource(ChangePasswordAPI, "/change_password")
api.add_resource(NoticeImageUploadAPI, "/notice/upload")

@app.route("/hello")
def index():
    return "Hello, Flask!"


if __name__ == "__main__":
    # 只有你自己运行 python app.py 时才启动服务器
    app.run(debug=True, host='0.0.0.0', port=8000)